package com.ikun.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ikun.usercenter.common.BaseResponse;
import com.ikun.usercenter.common.ErrorCode;
import com.ikun.usercenter.domain.User;
import com.ikun.usercenter.domain.request.UserLoginRequest;
import com.ikun.usercenter.domain.request.UserRegisterRequest;
import com.ikun.usercenter.exception.BusinessException;
import com.ikun.usercenter.service.UserService;
import com.ikun.usercenter.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ikun.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.ikun.usercenter.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户接口
 * @author 顾琴
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if(userRegisterRequest == null)
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String GenshinUID = userRegisterRequest.getGenshinUID();
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,GenshinUID))
        {
            return null;
        }
        Long id = userService.userRegister(userAccount, userPassword, checkPassword,GenshinUID);
        return ResultUtils.success(id);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if(userLoginRequest == null)
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword))
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if(request == null)
        {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int id = userService.userLogout(request);
        return ResultUtils.success(id);

    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        User currentUser = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if(currentUser == null)
        {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Long userId = currentUser.getId();
        //TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safeUser = userService.getSafeUser(user);
        return ResultUtils.success(safeUser);
    }

    @CrossOrigin("*")
    @GetMapping("/test")
    public String test(){
        return "test";
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String userName,HttpServletRequest request){
        if(isAdmin(request))
        {
            throw new BusinessException(ErrorCode.NO_AUTH,"不是管理员，不可查看用户列表");
        }

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(userName))
        {
            lqw.like(User::getUsername,userName);
        }

        List<User> userList = userService.list(lqw);
        List<User> userList1 = userList.stream().map(user -> userService.getSafeUser(user)).collect(Collectors.toList());
        return ResultUtils.success(userList1);
    }

    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable long id,HttpServletRequest request){
        if (isAdmin(request)) return null;

        if(id <= 0 )
            throw new BusinessException(ErrorCode.PARAMS_ERROR);

        boolean removeById = userService.removeById(id);
        return ResultUtils.success(removeById);
    }

    /**
     * 是否为管理员
     * @param request 请求本身
     */
    private  boolean isAdmin(HttpServletRequest request) {
        //仅管理员可查询
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return user == null || user.getUserRole() != ADMIN_ROLE;
    }


}
